package com.symbio.ishenapi.background.accessPlatform;


import com.symbio.ishenapi.background.accessPlatform.bean.PrivateData;
import com.symbio.ishenapi.background.accessPlatform.bean.PublicData;
import com.symbio.ishenapi.background.accessPlatform.bean.RequestMode;
import com.symbio.ishenapi.background.accessPlatform.exception.OpensnsException;
import com.symbio.ishenapi.background.accessPlatform.service.OpenApiV1;
import com.symbio.ishenapi.background.accessPlatform.util.StateData;
import com.symbio.ishenapi.background.accessPlatform.util.ValidataUtil;
import com.symbio.ishenapi.background.model.TmAccessToken;
import com.symbio.ishenapi.background.model.TmFlowNumber;
import com.symbio.ishenapi.background.util.util;
import com.symbio.ishenapi.common.controller.BaseController;
import io.jboot.web.controller.annotation.RequestMapping;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;


@RequestMapping("accessPlatformController")
public class accessPlatformController extends BaseController {


    /**
     * 开发票接口，飞
     *
     *
     */
    public void getAccessPlatform(){
        String orderNo = getPara("orderId");//订单id
        String email = getPara("email");//邮箱
        String pushMode = getPara("pushMode");//手机号
        String userName = getPara("userName");//开票人
        String price = getPara("price");//发票价格

        String token = TmAccessToken.dao.getToken();//查询token
        System.out.println(token);
        // 定义请求头数据
        Map<String,String> headers = getHeaders(token);
        PublicData pdData = getPublicData();
        PrivateData<Object> pvData = new PrivateData<Object>();
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        List<Map<String,Object>> list_invoiceDetail = new ArrayList<Map<String,Object>>();
        Map<String,Object> map_s = new HashMap<String,Object>();
        Map<String,Object> map_order = new HashMap<String,Object>();
        Map<String,Object> map_invoiceDetails = new HashMap<String,Object>();
        map_order.put("pushMode", "2");
        map_order.put("orderNo", System.currentTimeMillis() + "001");//订单号
        map_order.put("salerTaxNum", "91460100MA5T1GBCXH");//销方税号（使用沙箱环境请求时消息体参数salerTaxNum和消息头参数userTax填写339901999999142）
        map_order.put("salerAddress", "海南省海口市玉沙路28号宝发国际大厦7层 ");//销方地址
        map_order.put("salerTel", "66122400");//销方电话
        map_order.put("salerAccount","中国工商银行海口国贸支行 2201028109200112774");//销方银行账号和开户行地址
        map_order.put("email",email);//推送邮箱（pushMode为0或2时，此项为必填）
        map_order.put("clerk", "张三");//开票员
        map_order.put("payee", "李四");//收款人
        map_order.put("checker", "x李四");//复核人
        String date = util.dateToStrLong(new Date());
        map_order.put("invoiceDate",date);//订单时间
        map_order.put("buyerAddress", "");//购方地址（企业要填，个人可为空）
        map_order.put("buyerPhone", pushMode);//	购方手机（开票成功会短信提醒购方，不受推送方式影响）
        map_order.put("buyerTaxNum", "");//购方税号（企业要填，个人可为空）
        map_order.put("buyerName", userName);//购方名称
        map_order.put("buyerAccount", "");
        map_order.put("remark", "XXXXXXX");
        map_order.put("invoiceType", "1");
        map_order.put("invoiceCode", "");
        map_order.put("invoiceNum", "");
        map_order.put("remark", "");
        map_order.put("listFlag", "0");
        map_order.put("listName", "详见销货清单");
        map_order.put("proxyInvoiceFlag", "0");
        map_invoiceDetails.put("goodsName", "1");
        map_invoiceDetails.put("num", "1");
        map_invoiceDetails.put("withTaxFlag", "0");
        map_invoiceDetails.put("price", price);
        map_invoiceDetails.put("taxRate", "0");
        map_invoiceDetails.put("specType", "1");
        map_invoiceDetails.put("unit", "1");
        map_invoiceDetails.put("goodsCode", "1090511030000000000");
        map_invoiceDetails.put("selfCode", null);
        map_invoiceDetails.put("invoiceLineProperty", "0");
        map_invoiceDetails.put("favouredPolicyFlag", "0");
        map_invoiceDetails.put("favouredPolicyName", null);
        map_invoiceDetails.put("zeroRateFlag", 1);
        map_invoiceDetails.put("deduction", null);
        map_invoiceDetails.put("tax", "0");
        map_invoiceDetails.put("taxIncludedAmount", price);
        map_invoiceDetails.put("taxExcludedAmount", price);
        list_invoiceDetail.add(map_invoiceDetails);
        map_order.put("invoiceDetail", list_invoiceDetail);
        map_s.put("order", map_order);
        list.add(map_s);
        pvData.setServicedata(list);
        RequestMode requestMode = getRequestMode(pdData,pvData);
        OpenApiV1 sdk =  new OpenApiV1();
        String result = null;
        try {
            // 调用服务
            result = sdk.handle(StateData.url, headers, requestMode);
            if (!ValidataUtil.isEmpty(result)) {
               /* System.out.println("服务端的响应：" + result);
                String s1 = result.replaceAll("\\\\", "\"").replaceAll("\"", "");//截掉\和""
                System.out.println(s1);*/
                //json字符串转换成json对象
                System.out.println(result);
                JSONObject jsonObj1 = new JSONObject(result);
                String code = jsonObj1.get("code").toString();
                System.out.println( "-----__++++>"+code);
                if ("E0000".equals(code)) {
                    JSONObject personObj1 = jsonObj1.getJSONObject("result");
                    Object access_token = personObj1.get("invoiceSerialNum");
                    System.out.println(access_token);
                    //保存到数据库里
                    TmFlowNumber tmFlowNumber = new TmFlowNumber();
                    tmFlowNumber.setInvoiceSerialNum(access_token.toString());
                    tmFlowNumber.setStatus(1L);
                    tmFlowNumber.setCreateTime(new Date());
                    tmFlowNumber.setEmail(email);
                    tmFlowNumber.setOrderNo(new BigInteger(orderNo));
                    tmFlowNumber.save();
                }
            }
        } catch (OpensnsException e) {
            System.out.printf("Request failed 【" + e.getErrorCode() + ":" + e.getMessage() + "】");
            e.printStackTrace();
        }
        renderJson(result);
    }

    /**
     * 通过开票流水号查询电子发票明细，支持批量查询
     *
     * @paramargs
     * @throws OpensnsException
     */
    public void getPlatform() throws OpensnsException{
    /*public static void main(String[] args) throws OpensnsException{*/
        String no = getPara("invoiceSerialNum");//流水号
        String token = TmAccessToken.dao.getToken();//查询token
        System.out.println(token);
        Map<String,String> headers = getHeaders(token);
        PublicData pdData = getPublicDatas();
        PrivateData<Object> pvData = new PrivateData<Object>();
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        List<String> list_s = new ArrayList<String>();
        Map<String,Object> map_s = new HashMap<String,Object>();
        //拆分，然后遍历
        String num[] = no.split(",");
        for(int i=0;i < num.length;i++){
            list_s.add(num[i]);
        }

        map_s.put("invoiceSerialNum", list_s);
        list.add(map_s);
        pvData.setServicedata(list);
        RequestMode requestMode = getRequestMode(pdData,pvData);
        OpenApiV1 sdk = new OpenApiV1();
        String result = sdk.handle(StateData.url,headers, requestMode);
        System.out.println(result);
        renderJson(result);
        return;
    }

    // 定义请求头数据
    private static Map<String, String> getHeaders(String token) {

        Map<String, String> headers = new HashMap<String, String>();
        System.out.println(StateData.app_key);
        headers.put("appKey", StateData.app_key); // 用户申请的appkey
        headers.put("app_secret", "295D8D42FC9040BF");
        headers.put("accessToken", token); // 用户Oauth登录后得到的令牌accessToken
        headers.put("compress", StateData.app_compressType);// 压缩方式：提供GZIP 置空“”不压缩
        headers.put("signMethod", StateData.app_signType); // 加密方式：提供AES/AES，不可为空
        headers.put("dataType", StateData.app_dataType); // 数据请求格式： JSON/XML
        headers.put("appRate", StateData.app_rate); // app并发请求数 ，平台默认10如需升级请联系开放平台
        headers.put("userTax", StateData.user_Tax); // ISV下商家需要填写当前商户税号，普通商家模式用户可以不填写此值
        headers.put("Content-Type", StateData.contentType); // http发送模式
        return headers;
    }

    // 定义请求体中的公共数据,这是开发票用
    private static PublicData getPublicData() {
        PublicData pdData = new PublicData();
        pdData.setVersion(StateData.app_apiVersion); // API版本
        pdData.setTimestamp(String.valueOf(System.currentTimeMillis()));
        pdData.setMethod("nuonuo.electronInvoice.requestBilling");// API名称
        return pdData;
    }

    // 定义请求体中的公共数据，这是通过流水号查询发票用
    private static PublicData getPublicDatas() {
        PublicData pdData = new PublicData();
        pdData.setVersion(StateData.app_apiVersion); // API版本
        pdData.setTimestamp(String.valueOf(System.currentTimeMillis()));
        pdData.setMethod("nuonuo.electronInvoice.CheckEInvoice");// API名称
        return pdData;
    }

    private static RequestMode getRequestMode(PublicData pdata, PrivateData<Object> pvData) {
        RequestMode requestMode = new RequestMode();
        requestMode.setPrivate(pvData);
        requestMode.setPublic(pdata);
        return requestMode;
    }
}
